﻿using System.Configuration;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nvigorate.Aspect;
using Nvigorate.Data;
using Nvigorate.Data.Query;
using Nvigorate.Relational.Mapping;
using Nvigorate.Relational.Mapping.Index;
using Nvigorate.Relational.Record;
using Nvigorate.Relational.State;

namespace Nvigorate.Test.TSQL
{
    /// <summary>
    /// Summary description for InformationSchemaTests
    /// </summary>
    [TestClass]
    public class InformationSchemaTests
    {
        public InformationSchemaTests()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test 
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void GetForeignKeys()
        {
            var mapindex = new MapIndex();

            var database = new DataInterface(ConfigurationManager.ConnectionStrings["simple"]);
            var query = Select.Query(
                            Table.From("sys.foreign_key_columns").As("k")
                                .Join
                                (
                                    Table.InnerJoin("sys.objects").As("parent")
                                        .On(Criterion.Column("OBJECT_ID", "parent").EqualTo(Column.Named("parent_object_id").OwnedBy("k"))),
                                    Table.InnerJoin("sys.objects").As("ref")
                                        .On(Criterion.Column("OBJECT_ID", "ref").EqualTo(Column.Named("referenced_object_id").OwnedBy("k"))),
                                    Table.InnerJoin("sys.columns").As("pCol")
                                        .On(
                                                Criterion.Column("OBJECT_ID", "pCol").EqualTo(Column.Named("parent_object_id").OwnedBy("k")) &
                                                Criterion.Column("column_ID", "pCol").EqualTo(Column.Named("parent_column_id").OwnedBy("k"))
                                            ),
                                    Table.InnerJoin("sys.columns").As("rCol")
                                        .On(
                                                Criterion.Column("OBJECT_ID", "rCol").EqualTo(Column.Named("referenced_object_id").OwnedBy("k")) &
                                                Criterion.Column("column_ID", "rCol").EqualTo(Column.Named("referenced_column_id").OwnedBy("k"))
                                            )
                                )
                    ,
                Column.Named("*").OwnedBy("k") +
                Column.Named("Name").OwnedBy("parent").As("ParentTableName") +
                Column.Named("Name").OwnedBy("pCol").As("ParentColumnName") +
                Column.Named("Name").OwnedBy("ref").As("ReferencedTableName") +
                Column.Named("Name").OwnedBy("rCol").As("ReferencedColumnName")
                
            ).Top((Literal)10);

            var commandText = query.Translate(database.Provider);

            var table = database.GetTable(query, "foreignKeys", mapindex.GetRepositoryMapIndex(""));
            var rows = (DataRecordCollection) table;
            if(rows.Count == 0)
                return;
            var binder = BindingLambdaFactory.GetBindingLambda<Test>("", rows[1]);

            var collection = rows.Select(binder);

            var targetRow = rows.Where(r => r["ParentTableName"].ToString() == "Employees").ToList();

            var targetInstance = collection.Where(i => i.ParentTableName == "Employees").FirstOrDefault();

            Assert.IsNotNull(targetInstance);
            Assert.IsTrue(targetRow.Count == 1);

            Assert.IsTrue(table.Rows.Count > 0);
        }

    }

    [StateTrackingAspect]
    public class Test : StateTracking
    {
        public string ParentTableName { get; set; }
        public string ParentColumnName { get; set; }
        public string ReferencedTableName { get; set; }
        public string ReferencedColumnName { get; set; }
    }
}
